<?php

namespace app\common\library;

use think\Env;
use think\Exception;

class Faceid
{
    // 腾讯云密钥
    protected $_secretId = '';
    protected $_secretKey = '';

    public function __construct()
    {
        $this->_secretId = Env::get('tencentcloud.secretid');
        $this->_secretKey = Env::get('tencentcloud.secretkey');
    }

    public function checkNameAndIdCard($name = '', $idCard = '')
    {
        $res = [
            'msg' => 'ok',
            'data' => [],
        ]; 
        if (empty($name) || empty($idCard)) {
            $res['msg'] = '缺少参数';

            return $res;
        }

        $secret_id = $this->_secretId;
        $secret_key = $this->_secretKey;
        $params = ['Name' => $name, 'IdCard' => $idCard];
        $token = "";

        $service = "faceid";
        $host = "faceid.tencentcloudapi.com";
        $req_region = "ap-guangzhou";
        $version = "2018-03-01";
        $action = "IdCardOCRVerification";

        $payload = json_encode($params);
        $endpoint = "https://faceid.tencentcloudapi.com";
        $algorithm = "TC3-HMAC-SHA256";
        $timestamp = time();
        $date = gmdate("Y-m-d", $timestamp);

        $http_request_method = "POST";
        $canonical_uri = "/";
        $canonical_querystring = "";
        $ct = "application/json; charset=utf-8";
        $canonical_headers = "content-type:".$ct."\nhost:".$host."\nx-tc-action:".strtolower($action)."\n";
        $signed_headers = "content-type;host;x-tc-action";
        $hashed_request_payload = hash("sha256", $payload);
        $canonical_request = "$http_request_method\n$canonical_uri\n$canonical_querystring\n$canonical_headers\n$signed_headers\n$hashed_request_payload";

        $credential_scope = "$date/$service/tc3_request";
        $hashed_canonical_request = hash("sha256", $canonical_request);
        $string_to_sign = "$algorithm\n$timestamp\n$credential_scope\n$hashed_canonical_request";

        $secret_date = $this->sign("TC3".$secret_key, $date);
        $secret_service = $this->sign($secret_date, $service);
        $secret_signing = $this->sign($secret_service, "tc3_request");
        $signature = hash_hmac("sha256", $string_to_sign, $secret_signing);

        $authorization = "$algorithm Credential=$secret_id/$credential_scope, SignedHeaders=$signed_headers, Signature=$signature";

        $headers = [
            "Authorization" => $authorization,
            "Content-Type" => "application/json; charset=utf-8",
            "Host" => $host,
            "X-TC-Action" => $action,
            "X-TC-Timestamp" => $timestamp,
            "X-TC-Version" => $version
        ];
        if ($req_region) {
            $headers["X-TC-Region"] = $req_region;
        }
        if ($token) {
            $headers["X-TC-Token"] = $token;
        }

        try {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $endpoint);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array_map(function ($k, $v) { return "$k: $v"; }, array_keys($headers), $headers));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $response = curl_exec($ch);
            curl_close($ch);

            $responseData  = json_decode($response, true);
            if (isset($responseData['Response'])) {
                $responseData = $responseData['Response'];
                if (isset($responseData['Error'])) {
                    $res['msg'] = $responseData['Error']['Code'];
                } else {
                    if ($responseData['Result'] == '0') {
                        $res['data'] = [
                          'Name' => $responseData['Name'],
                          'IdCard' => $responseData['IdCard'],
                        ];
                    } else {
                        $res['msg'] = $responseData['Description'];
                    }
                }
            } else {
                $res['msg'] = '数据返回解析失败, 请稍后再试';
            }
        } catch (Exception $err) {
            $msg = $err->getMessage();
            $res['msg'] = '系统错误，请稍后再试';
        }

        return $res;
    }

    private function sign($key, $msg) {
        return hash_hmac("sha256", $msg, $key, true);
    }
}
